package com.hnu.tockmarket.activity;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import com.google.gson.Gson;
import com.hnu.tockmarket.R;
import com.hnu.tockmarket.constant.SystemConstants;
import com.hnu.tockmarket.entity.User;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * 修改密码页面对应的活动
 *
 * @author hnulht
 * @since 2021-07-08
 */
public class UserChangePasswordActivity extends AppCompatActivity implements View.OnClickListener {

    private static final String TAG = "UserChangePasswordActivity"; // 日志
    private Intent intent = null;
    private EditText editTextNewPassword; // 用户新密码输入框
    private EditText editTextConfirmPassword; // 用户确认新密码输入框
    private Button buttonConfirm; // 确认按钮
    private Button buttonClear; // 清空按钮
    private Toolbar toolbar; // 工具栏
    private ProgressDialog progressDialog; // 修改加载控件
    private static final int UPDATE_OK = 1; // 表示用户密码修改成功
    private static final int UPDATE_ERROR = 0; // 表示用户密码修改失败
    private String inputNewPassword = ""; // 临时存储用户输入的新密码
    private String inputConfirmPassword = ""; // 临时存储用户输入的确认新密码
    private final SystemHandler systemHandler = new SystemHandler(); // 将数据从子线程抛到主线程中

    private class SystemHandler extends Handler {
        @SuppressLint("LongLogTag")
        @Override
        public void handleMessage(@NonNull Message message) {
            super.handleMessage(message);
            switch (message.what) {
                case UPDATE_OK:
                    Log.d(TAG, "[SystemHandler.handleMessage]主线程处理子线程传送的信息" + (String) message.obj);
                    // 解析服务器传回的JSON格式数据
                    String restResponse = (String) message.obj;
                    parseJSON(restResponse);
                    break;
                case UPDATE_ERROR:
                    Log.d(TAG, "[SystemHandler.handleMessage]主线程处理子线程传送的信息" + (String) message.obj);
                    break;
                default:
                    break;
            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState); // 调用父类onCreate()方法
        setContentView(R.layout.activity_user_change_password); // 给修改密码页面活动加载对应的布局
        initView(); // 初始化视图
    }

    /**
     * 初始化视图
     */
    private void initView() {
        // 定位工具栏并设置点击事件
        toolbar = (Toolbar) findViewById(R.id.user_change_password_tb);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        // 定位用户新密码和确认新密码输入框
        editTextNewPassword = (EditText) findViewById(R.id.user_change_password_new_password_et);
        editTextConfirmPassword = (EditText) findViewById(R.id.user_change_password_confirm_password_et);
        // 定位用户确认按钮并设置点击事件
        buttonConfirm = (Button) findViewById(R.id.user_change_password_confirm_btn);
        buttonConfirm.setOnClickListener(this);
        // 定位清空按钮并设置点击事件
        buttonClear = (Button) findViewById(R.id.user_change_password_clear_btn);
        buttonClear.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.user_change_password_confirm_btn:
                checkUserUpdate(); // 检查用户提交的修改信息
                break;
            case R.id.user_change_password_clear_btn:
                editTextNewPassword.setText("");
                editTextConfirmPassword.setText("");
                break;
        }
    }

    /**
     * 检查用户提交的修改信息
     */
    private void checkUserUpdate() {
        inputNewPassword = editTextNewPassword.getText().toString().trim(); // 获取用户输入的新密码
        if (TextUtils.isEmpty(inputNewPassword)) {
            Toast.makeText(UserChangePasswordActivity.this, "请输入新密码", Toast.LENGTH_SHORT).show();
            return;
        }
        inputConfirmPassword = editTextConfirmPassword.getText().toString().trim(); // 获取用户输入的确认新密码
        if (TextUtils.isEmpty(inputConfirmPassword)) {
            Toast.makeText(UserChangePasswordActivity.this, "请确认新密码", Toast.LENGTH_SHORT).show();
            return;
        }
        if (!inputConfirmPassword.equals(inputNewPassword)) { // 确认新密码不等于新密码
            Toast.makeText(UserChangePasswordActivity.this, "两次输入不一致, 请重新输入", Toast.LENGTH_SHORT).show();
            editTextNewPassword.setText("");
            editTextConfirmPassword.setText("");
            return;
        }
        new Thread(new Runnable() {
            @SuppressLint("LongLogTag")
            @Override
            public void run() {
                try {
                    // 向服务器发送请求
                    String url = SystemConstants.SERVER_BASE_URL + "/user/updateUserPassword";
                    OkHttpClient okHttpClient = new OkHttpClient();
                    // 封装请求信息为json对象
                    SharedPreferences sharedPreferences = getSharedPreferences("login_data", MODE_PRIVATE);
                    Gson gson = new Gson();
                    User user = new User();
                    user.setId(sharedPreferences.getString("id", ""));
                    user.setName(sharedPreferences.getString("name", ""));
                    user.setPassword(inputConfirmPassword);
                    user.setRole(sharedPreferences.getString("role", ""));
                    user.setPhoneNumber(sharedPreferences.getString("phoneNumber", ""));
                    user.setEmail(sharedPreferences.getString("email", ""));
                    user.setSalt(sharedPreferences.getString("salt", ""));
                    user.setLastLoginTime(sharedPreferences.getString("lastLoginTime", ""));
                    user.setCreateTime(sharedPreferences.getString("createTime", ""));
                    user.setUpdateTime(sharedPreferences.getString("updateTime", ""));
                    // 构建请求体
                    MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
                    RequestBody requestBody = RequestBody.create(mediaType, gson.toJson(user));
                    Request request = new Request.Builder().url(url).put(requestBody).build();
                    // 服务器传回的响应信息
                    Response response = okHttpClient.newCall(request).execute();
                    assert response.body() != null;
                    String restResponse = response.body().string();
                    Log.d(TAG, "[checkUserLogin.run]子线程得到服务器传回的JSON数据" + restResponse);
                    // 向主线程发送服务器传回的响应信息
                    Message message = new Message();
                    message.what = UPDATE_OK;
                    message.obj = restResponse;
                    systemHandler.sendMessage(message);
                } catch (IOException e) {
                    Message message = new Message();
                    message.what = UPDATE_ERROR;
                    message.obj = e.getMessage();
                    systemHandler.sendMessage(message);
                    e.printStackTrace();
                }
            }
        }).start();
    }

    /**
     * 解析服务器传回的JSON格式数据
     *
     * @param restResponse JSON格式数据
     */
    @SuppressLint("LongLogTag")
    private void parseJSON(String restResponse) {
        try {
            Log.d(TAG, "[parseJSON]主线程解析服务器传回的JSON格式数据" + restResponse);
            JSONObject jsonObject = new JSONObject(restResponse);
            if (jsonObject.getInt("statusCode") == 200) {
                // 把修改信息保存到本地
                SharedPreferences.Editor editor = getSharedPreferences("login_data", MODE_PRIVATE).edit();
                editor.putString("password", inputConfirmPassword);
                editor.apply();
                // 定位修改加载控件并设置延时取消
                progressDialog = new ProgressDialog(UserChangePasswordActivity.this);
                progressDialog.setMessage("修改中...");
                progressDialog.setCancelable(false);
                progressDialog.show();
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Thread.sleep(2000); // 显示2秒后取消加载
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        progressDialog.dismiss();
                        Intent intent = new Intent(UserChangePasswordActivity.this, LoginActivity.class);
                        startActivity(intent);
                        finish();
                    }
                }).start();
            } else {
                Toast.makeText(UserChangePasswordActivity.this, "服务器内部错误", Toast.LENGTH_SHORT).show();
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

}